package www.sofn.com.goods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import www.sofn.com.domain.vo.PageRestVO;
import www.sofn.com.goods.domain.po.GoodsPO;
import www.sofn.com.goods.domain.query.GoodsQueryVO;
import www.sofn.com.goods.domain.vo.GoodsListVO;
import www.sofn.com.goods.domain.vo.GoodsVO;
import www.sofn.com.utils.GoodsUtils;
import www.sofn.com.utils.PageUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class GoodsService {

    @Autowired
    private GoodsMapper mapper;
    public PageRestVO<GoodsListVO> listPage(GoodsQueryVO query) {
        final Page<GoodsListVO> goodsListVOPage = mapper.listPage(new Page(query.getCurrent(), query.getSize()), query);
        goodsListVOPage.getRecords().stream().forEach(v->{
                v.setGoodsDefaultImg(GoodsUtils.getGoodsDefaultImg(v.getGoodsDefaultImg()));
        });
        return  PageUtils.toPageVO( goodsListVOPage );

    }



    //获取商品详情
    @Cacheable(value = "goods", key = "#root.args[0]")
    public GoodsVO getById(String id) {
        final GoodsPO goodsPO = mapper.selectById(id);
        return BeanUtil.toBean(goodsPO, GoodsVO.class);
    }

    //新增商品
    @Transactional
    public void  insert(GoodsPO goodsPO) {
        installAttrId(goodsPO.getGoodsAttr().getAttrValue());
        goodsPO.setPublishDate(LocalDateTime.now());
        mapper.insert(goodsPO);
    }
    //编辑商品
    @Transactional
//    @CacheEvict(value = "goods", key = "#root.args[0].id")
//    @CacheEvict(value = "goods" ,allEntries = true)
    @Caching(evict={@CacheEvict(value = "goods", key = "#root.args[0]"),
            @CacheEvict(value = "goods", key = "'displayInfo:'+#root.args[0].id")  })
    public void updateById(GoodsPO goodsPO) {
        installAttrId(goodsPO.getGoodsAttr().getAttrValue());
        goodsPO.setPublishDate(LocalDateTime.now());
        mapper.updateById(goodsPO);
    }

    //生成规格id
    private  void installAttrId(List<GoodsPO.AttrInfo> attrValue){
        attrValue.forEach(v->{
            v.setId(IdUtil.getSnowflakeNextId());
        });
    }

    //商品商品
    @Transactional
    public void delById(@NotNull Serializable id){
        mapper.deleteById(id);
    }


}
